﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Westwind.Web.JsonSerializers;
using SqlShareAPI;

namespace WebQueryRole
{
    public partial class sqlshare_master : System.Web.UI.MasterPage
    {
        public const string USER_QUERIES = "user_queries";
        public const string USER_TABLES = "user_tables";
        public const string USER_SESSION = "_session";

        // javascript variables loaded on page load
        protected string _jsonQueries = "null";
        protected string _jsonTables = "null";
        protected string _jsonUser = "null";

        private SSAPIFactory _factory;
        protected UserSession _session;

        protected override void OnInit(EventArgs e)
        {
            _factory = CloudUtil.CreateSSAPIFactory();
            _session = WebAuthentication.IsLoggedIn(this, _factory);
            Session[USER_SESSION] = _session;

            // populate queries and tables to session
            List<UserQuery> queries = _session.GetAllQueries();
            List<UserTable> tables = _session.GetAllTables();

            Session[USER_QUERIES] = queries;
            Session[USER_TABLES] = tables;

            JSONSerializer ser = new JSONSerializer();
            _jsonQueries = ser.Serialize(queries);
            _jsonTables = ser.Serialize(tables);
            _jsonUser = ser.Serialize(_session.User);

            // add current user info
            divCurUser.InnerHtml = "You are logged in as " + _session.UserName + " (" + _session.FullName + ") <a href=\"login.aspx?action=logout&token=" + Server.UrlEncode(_session.Token) + "\">logout</a>";            

            base.OnInit(e);            
        }

        protected override void OnUnload(EventArgs e)
        {
            _factory.Close();
            base.OnUnload(e);            
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            
        }
    }
}